<template>
  <div class="aui-card-list">
    <uni-list-query-card :queryShow="queryShow" @query-click="getDataList()" @click="(e)=>{this.queryShow=e}"
      @searchReset="searchReset()">
      <el-col :span="6">
        <el-form-item :label="$t('model.name')">
          <el-input v-model="dataForm.name" :placeholder="$t('model.name')" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item :label="$t('model.key')">
          <el-input v-model="dataForm.modelKey" :placeholder="$t('model.key')" clearable></el-input>
        </el-form-item>
      </el-col>
    </uni-list-query-card>
    <el-card shadow="never" class="aui-card-list-body">
      <vxe-toolbar :setting="{immediate:true}">
        <template v-slot:buttons>
          <el-button type="primary" @click="addOrUpdateHandle()">{{ $t('add') }}</el-button>
          <el-button type="danger" @click="deleteHandle()">{{ $t('deleteBatch') }}</el-button>
          <el-button @click="importBpm()">导入模型</el-button>
        </template>
        <template v-slot:tools>
          <el-button icon="el-icon-refresh" @click="getDataList()" circle></el-button>
        </template>
      </vxe-toolbar>
      <div class="aui-card-list-body-table">
        <vxe-table :loading="dataListLoading" :data="dataList" ref="xTable" auto-resize class="vxe-table-element"
          remote-sort @sort-change="dataListSortChangeHandle" @select-change="dataListSelectionChangeHandleVex"
          @select-all="dataListSelectionAllChangeHandleVex" max-height="auto">
          <vxe-table-column type="checkbox" width="50" align="center"></vxe-table-column>
          <vxe-table-column field="name" title="model.name"></vxe-table-column>
          <vxe-table-column field="modelKey" title="model.key"></vxe-table-column>
          <vxe-table-column field="created" title="model.createTime" width="140" align="center"></vxe-table-column>
          <vxe-table-column field="lastUpdated" title="model.lastUpdateTime" width="140" align="center">
          </vxe-table-column>
          <vxe-table-column title="handle" header-align="center" align="center" width="200">
            <template slot-scope="scope">
              <a :href="getModelerURL(scope.row.id)" target="_blank"
                class="el-button el-button--text el-button--small"><i
                  class="el-icon-tickets"></i><span>{{ $t('model.design') }}</span></a>
              <el-button type="text" icon="el-icon-delete" size="small" @click="deleteHandle(scope.row.id)">
                {{ $t('delete') }}
              </el-button>
              <el-divider direction="vertical"></el-divider>
              <el-dropdown split-button type="text" size="small">
                {{ $t('more')}}
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <el-button type="text" icon="el-icon-sold-out" size="small" @click="deployHandle(scope.row.id)">
                      {{ $t('model.deploy') }}
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button type="text" icon="el-icon-download" size="small" @click="getExportURL(scope.row.id)">
                      {{ $t('export') }}
                    </el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </vxe-table-column>
        </vxe-table>
        <el-pagination :current-page="page" :page-sizes="[10, 20, 50, 100]" :page-size="limit" :total="total"
          layout="total, sizes, prev, pager, next, jumper" @size-change="pageSizeChangeHandle"
          @current-change="pageCurrentChangeHandle">
        </el-pagination>
        <!-- 弹窗, 新增 / 修改 -->
        <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
        <model-imp v-if="importVisible" ref="modelImp" @refreshDataList="getDataList"></model-imp>
      </div>
    </el-card>
  </div>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import AddOrUpdate from './model-add-or-update'
import modelImp from './modelImp'

import qs from 'qs'
export default {
  mixins: [mixinViewModule],
  data () {
    return {
      mixinViewModuleOptions: {
        getDataListURL: '/act/model/page',
        getDataListIsPage: true,
        deleteURL: '/act/model',
        deleteIsBatch: true
      },
      nodeVisible: false,
      importVisible: false,
      dataForm: {
        name: '',
        modelKey: ''
      }
    }
  },
  components: {
    AddOrUpdate,
    modelImp
  },
  methods: {
    // 获取在线设计url地址
    getModelerURL (id) {
      var params = qs.stringify({
        token: this.$cookies.get('token')
      })
      return `${window.SITE_CONFIG['apiURL']}/modler/index#/editor/` + id + `?${params}`
    },
    // 工作流模型导入
    importBpm () {
      this.importVisible = true
      this.$nextTick(() => {
        this.$refs.modelImp.init()
      })
    },
    // 获取导出url地址
    getExportURL (id) {
      this.dataListLoading = true
      this.$http.get(`/act/model/export/${id}`).then(({ data: res }) => {
        this.dataListLoading = false
        if (res.code !== 0) {
          return false
        }
        this.downloadFile(res.data.fileName, res.data.fileBase64)
      })
    },
    // 下载
    downloadFile (fileName, content) {
      var aLink = document.createElement('a')
      var blob = this.base64ToBlob(content)
      var evt = document.createEvent('HTMLEvents')
      evt.initEvent('click', true, true)
      aLink.download = fileName
      aLink.href = URL.createObjectURL(blob)
      aLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }))
    },
    // base64转blob
    base64ToBlob (code) {
      var parts = code.split(';base64,')
      var contentType = parts[0].split(':')[1]
      var raw = window.atob(parts[1])
      var rawLength = raw.length
      var uInt8Array = new Uint8Array(rawLength)
      for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], { type: contentType })
    },
    // 部署
    deployHandle (id) {
      this.$confirm(this.$t('prompt.info', { 'handle': this.$t('model.deploy') }), this.$t('prompt.title'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        this.$http.post(`/act/model/deploy/${id}`).then(({ data: res }) => {
          if (res.code !== 0) {
            return
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.getDataList()
            }
          })
        }).catch(() => { })
      }).catch(() => { })
    }
  }
}
</script>
